const path = require('path')

// 修复pkg打包后无法找到Prisma Client的问题
let PrismaClient
let prisma

// 尝试不同的导入路径以适应pkg打包环境
if (process.pkg) {
  try {
    // 对于pkg打包环境，尝试直接从snapshot路径导入
    PrismaClient = require('@prisma/client').PrismaClient
  } catch (error) {
    // 如果失败，尝试使用绝对路径导入
    try {
      const clientPath = path.join(
        path.dirname(process.execPath),
        'node_modules',
        '@prisma',
        'client'
      )
      PrismaClient = require(clientPath).PrismaClient
    } catch (innerError) {
      console.error('无法在pkg打包环境中加载Prisma Client:', innerError)
      throw innerError
    }
  }
} else {
  // 非打包环境直接导入
  PrismaClient = require('@prisma/client').PrismaClient
}

// 根据操作系统选择正确的 Prisma 查询引擎文件
function getPrismaEngineFilename() {
  // 更多可参考 https://www.prisma.io/docs/orm/reference/prisma-schema-reference#binarytargets-options
  switch (process.platform) {
    case 'darwin': // macOS
      return 'libquery_engine-darwin.dylib.node'
    case 'linux': // Linux
      return 'libquery_engine-rhel-openssl-1.1.x.so.node'
    case 'win32': // Windows
      return 'query_engine-windows.dll.node'
    default:
      throw new Error(`Unsupported platform: ${process.platform}`)
  }
}

// 配置Prisma以在pkg打包环境中找到查询引擎
prisma = new PrismaClient({
  __internal: {
    engine: {
      binaryPath: process.pkg
        ? path.join(
            path.dirname(process.execPath),
            'node_modules',
            '.prisma',
            'client',
            getPrismaEngineFilename()
          ) //路径需要根据 src/model/prisma/prisma.prisma 中的 output 配置
        : undefined,
    },
  },
})

module.exports = prisma
